﻿using MaiPlanServer.IRepository;
using MaiPlanServer.IServices.IMasterDataServices;
using MaiPlanServer.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MaiPlanServer.Services.MasterDataServices
{
    public class CodingRulesServices : ICodingRulesServices
    {

        public CodingRulesServices(IBaseRepository BaseConn)
        {
            this.BaseConn = BaseConn;
        }

        public IBaseRepository BaseConn { get; }


        public async Task<bool> AddAsync(SYS_AUTO_CODE_RULE model)
        {
            var result = await BaseConn.InsertAsync(model);
            return result;
        }


        public async Task<bool> DellAsync(string ruleId)
        {
            string sql = "delete SYS_AUTO_CODE_RULE where RULE_ID = @ruleId";
            var result = await BaseConn.DeleteAsync(sql, new { ruleId });
            return result;
        }

        public async Task<bool> DellAllAsync(string[] ruleId)
        {
            string sql = "delete SYS_AUTO_CODE_RULE where RULE_ID in @ruleId";
            var result = await BaseConn.DeleteAsync(sql, new { ruleId });
            return result;
        }


        public async Task<IEnumerable<SYS_AUTO_CODE_RULE>> GetJsonAsync(int PageIndex, int PageSize, string ruleCode, string ruleName, string State)
        {
            string sql = @"select * from SYS_AUTO_CODE_RULE where 1=1 and RULE_NAME like @ruleName and RULE_CODE like @ruleCode ";
            if (!string.IsNullOrEmpty(State))
            {
                sql += " and ENABLE_FLAG = @State ";
            }
            sql += " order by Create_Time desc offset @PageSize*(@PageIndex-1) rows fetch next @PageSize row only";

            var list = await BaseConn.QueryAsync<SYS_AUTO_CODE_RULE>(sql, new { PageIndex, PageSize, ruleCode = "%" + ruleCode + "%", ruleName = "%" + ruleName + "%", State });

            return list;
        }

        public async Task<int> GetCountAsync(string ruleName)
        {
            string sql = @"select count(1) from SYS_AUTO_CODE_RULE where 1=1 and RULE_NAME like @ruleName ";

            var count = await BaseConn.GetRecoreCountAsync(sql, new {ruleName = "%" + ruleName + "%" });

            return count;
        }



        public async Task<bool> UpdateAsync(SYS_AUTO_CODE_RULE model)
        {
            var result = await BaseConn.UpdateAsync(model,"RULE_ID");

            return result;
        }

    }
}
